package cc.iotkit.jql;

import cc.iotkit.jql.annotation.JqlQuery;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.GenericBeanDefinition;

import java.util.Set;

public class JqlQueryConfiguration implements BeanDefinitionRegistryPostProcessor {

    /**
     * 查询接口扫描包
     */
    private String queryPackage;

    public JqlQueryConfiguration(String queryPackage) {
        this.queryPackage = queryPackage;
    }

    public void run(BeanDefinitionRegistry registry) {
        Set<Class<?>> scanPackage = ClassUtil.scanPackageByAnnotation(queryPackage, JqlQuery.class);
        for (Class<?> cls : scanPackage) {
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(cls);
            GenericBeanDefinition definition = (GenericBeanDefinition) builder.getRawBeanDefinition();
            definition.getPropertyValues().add("interfaceClass", definition.getBeanClassName());
            definition.setBeanClass(JqlBeanFactory.class);
            definition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE);
            String beanName = StrUtil.removePreAndLowerFirst(cls.getSimpleName(), 0) + "Proxy";
            registry.registerBeanDefinition(beanName, definition);
        }
    }

    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        run(registry);
    }

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    }
}
